package com.ruoyi.common.dao.service;

import com.ruoyi.common.core.domain.WorkerNodeEntity;
import com.xfvape.uid.utils.DockerUtils;
import com.xfvape.uid.utils.NetUtils;
import com.xfvape.uid.worker.WorkerIdAssigner;
import com.xfvape.uid.worker.WorkerNodeType;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.transaction.Transactional;
import java.util.Date;

public class MyDisposableWorkerIdAssigner implements WorkerIdAssigner {
    @Autowired
    private SysWorkerNodeDao workerNodeDao;
    @Override
    @Transactional
    public long assignWorkerId() {
        // build worker node entity
		//别导入错了，导入刚才复制的WorkerNodeEntity类
        WorkerNodeEntity workerNodeEntity = buildWorkerNode();

        // add worker node for new (ignore the same IP + PORT)
        workerNodeDao.addWorkerNode(workerNodeEntity);

        return workerNodeEntity.getId();
    }
    private WorkerNodeEntity buildWorkerNode() {
        WorkerNodeEntity workerNodeEntity = new WorkerNodeEntity();
        if (DockerUtils.isDocker()) {
            workerNodeEntity.setType(WorkerNodeType.CONTAINER.value());
            workerNodeEntity.setHostName(DockerUtils.getDockerHost());
            workerNodeEntity.setPort(DockerUtils.getDockerPort());
        } else {
            workerNodeEntity.setType(WorkerNodeType.ACTUAL.value());
            workerNodeEntity.setHostName(NetUtils.getLocalAddress());
            workerNodeEntity.setPort(System.currentTimeMillis() + "-" + RandomUtils.nextInt(100000));
        }
        workerNodeEntity.setCreated(new Date());
        workerNodeEntity.setModified(new Date());
        workerNodeEntity.setLaunchDate(new Date());
        return workerNodeEntity;
    }
}
